package com.atguigu.controller;

import ch.qos.logback.core.util.TimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.constant.RedisConst;
import com.atguigu.entity.UserInfo;
import com.atguigu.result.RetVal;
import com.atguigu.service.UserInfoService;
import com.atguigu.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/login")
    public RetVal login(@RequestBody UserInfo uiUser, HttpServletRequest request){
        UserInfo dbUser=userInfoService.queryUserFromdb(uiUser);
        if (dbUser!=null){
            String token = UUID.randomUUID().toString();
            Map<String, Object> retValMap = new HashMap<>();
            retValMap.put("token", token);
            retValMap.put("nickName",dbUser.getLoginName());
            //将用户信息储存到redis中
            JSONObject logoinInfo = new JSONObject();
            logoinInfo.put("userId", dbUser.getId());
            logoinInfo.put("loginIp", IpUtil.getIpAddress(request));
            String userKey = RedisConst.USER_LOGIN_KEY_PREFIX+ token;
            redisTemplate.opsForValue().set(userKey, logoinInfo.toJSONString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return RetVal.ok(retValMap);
        }else {
            return RetVal.fail().message("登录失败");
        }

    }
    @GetMapping("logout")
    public RetVal logout(HttpServletRequest request){
        String s=RedisConst.USER_LOGIN_KEY_PREFIX+request.getHeader("token");
        redisTemplate.delete(s);
        return RetVal.ok();
    }
}

































